package com.qf.factory;

import com.qf.service.AccountService;
import com.qf.util.TransactionManager;
import sun.dc.pr.PRError;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @ClassName BeanFactory
 * @Description TODO
 * @Author 86181
 * @Date 2022/8/31 18:08
 * @Version 1.0
 **/
public class BeanFactory {
    private AccountService accountService;
    public  void setAccountService(AccountService accountService){
        this.accountService=accountService;
    }

    private TransactionManager transactionManager;
    public  void setTransactionManager(TransactionManager transactionManager){
        this.transactionManager=transactionManager;
    }

    //生成处理对象
    public  AccountService getBean(){
        AccountService o= (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
                accountService.getClass().getInterfaces(), new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if ("transfer".equals(method.getName())){
                    transactionManager.begin();
                    method.invoke(accountService,args);
                    transactionManager.commit();
                    transactionManager.rollback();
                    transactionManager.release();
                }
                return null;
            }

        });
        return o;
    }
}
